//
//  HMOAuthViewController.swift
//  MicroBlog
//
//  Created by Apple on 16/9/20.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
//第三方登录VC
//新浪开发平台提供的APPKey
let WeiBoAppKey = "2607220998"
//授权回调页
let WeiBoRedirect_URI = "http://www.itcast.cn"
//appSecret
let WeiboAppSecret = "bd8a9cb991b2f19c480cc3eef74e2843"
class HMOAuthViewController: UIViewController {
    //懒加载
    private lazy var webView: UIWebView = UIWebView()
    //重写LoadView:把webView作为VC的view
    override func loadView() {
        //解决底部黑条,改成透明
        webView.isOpaque = false
        webView.delegate = self;
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestLogin()
        setupNavUI()
    }
    
    //请求第三方登录
    private func requestLogin() {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiBoAppKey)&redirect_uri=\(WeiBoRedirect_URI)"
        let urlRequest = URLRequest(url: URL(string: url)!)
        webView.loadRequest(urlRequest)
    }
    
    //设置导航栏按钮
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", imageName: nil, target: self, action: #selector(autoFillAction))
        title = "贱客"
    }
    
    //点击事件
    @objc private func cancelAction() {
        //删除菊花
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        print("自动填充")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18271432322';document.getElementById('passwd').value = 'qingdesky523441@'")
    }
    
}
//网页代理
extension HMOAuthViewController: UIWebViewDelegate {
    //开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
    }
    //将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //截取字符串,判断url是否合法
        guard let url = request.url else {
            return false
        }
        print(url.absoluteString)
        if !url.absoluteString.hasPrefix(WeiBoRedirect_URI) {
            //不是想要的地址,让其加载
            return true
        }
        //代码执行到此表示是需要的请求地址
        //地址'?'后所有部分,用于取地址栏中的参数
        if let query = url.query , query.hasPrefix("code="){
            //截取字符串
            let code = query.substring(from: "code=".endIndex)
            //通过code获取accessToken
            HMUserAccountViewModel.sharedUserAccountViewModel.requestAccessToken(code: code, callBack: { (isTrue) in
                if isTrue{
                    print("登录成功")
                    //登录成功移除控制器,dismiss完成以后才发送通知
                    self.dismiss(animated: false, completion: {
                        //进入欢迎页面
                        NotificationCenter.default.post(name: Notification.Name(SwitchRootVCNotification), object: self)

                    })
                }
            })
        } else {
            //不是'code='开头的网址,取消授权
            dismiss(animated: true, completion: nil)
        }
        return true
    }
}
